package com.fzn3.day04;

/**
 * @author fzn
 * 描述：二分查找-递归
 * @program DataStructure
 * @create 2023/3/9 17:09
 **/
public class BinarySearch {
    public static int search(int[] a, int target) {
        return f(a, target, 0, a.length - 1);
    }

    /**
     * 递归(子问题) 二分查找
     *
     * @param a
     * @param target
     * @param i
     * @param j
     * @return int
     */
    private static int f(int[] a, int target, int i, int j) {
        if (i > j) {
            return -1;
        }
        int m = (i + j) >>> 1;
        if (target < a[m]) {
            return f(a, target, i, m - 1);
        } else if (a[m] < target) {
            return f(a, target, m + 1, j);
        } else {
            return m;
        }
    }
}
